/*
 * @Author: 郭招娣 10615594+guo-zhaodi@user.noreply.gitee.com
 * @Date: 2022-10-26 15:57:17
 * @LastEditors: 郭招娣 10615594+guo-zhaodi@user.noreply.gitee.com
 * @LastEditTime: 2022-10-31 09:23:50
 * @FilePath: \宏烨找房\user\demo\src\page\Service\index.jsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import React, { useState } from 'react'
import { Input, Button } from 'react-vant'
import "./index.css"

const Service = () => {
  const [value, setValue] = useState("")
  const [list, setList] = useState([])
  const ws = new WebSocket('ws://localhost:9000');

  const handleChange = (value) => {
    setValue(value)
  }
  const submit = () => {
    ws.send(value)
    setList([...list, { title: value }])

  }

  ws.onopen = function () {
    // 连接的时候触发
    if (ws.readyState === 1) {
      console.log('连接成功')
    }
  }

  ws.onmessage = function (msg) {
    setList([...list, { title: [msg.data] }])
  }

  return (
    <div className='new'>
      <div className="new-main">
        {
          list.length && list.map((v, i) => {
            return (
              <div key={i} className="item">
                <span className='aside'>用户</span>
                <div className="item-title">{v.title}</div>
              </div>
            )
          })

        }
      </div>
      <div className="new-footer">
        <Input
          placeholder="请输入文本"
          onChange={(value) => handleChange(value)}
        />
        <Button onClick={() => submit()}>发送</Button>
      </div>
    </div>
  )
}

export default Service